package com.example.uupaymuch.controller.notice.east;

import com.alibaba.fastjson.JSONObject;
import com.example.uupaymuch.controller.util.VerifySignUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class EastTransferComponent {

    private final String noticeTransfer = "http://localhost:27003/api/transfer/notify/colombiapay/eastpay";
//    private final String noticeTransfer = "https://pay-india.ssonicpay.com/api/transfer/notify/brazilpay/wudipay";
    private static final String HMAC_SECRET = "041a3722-81b6-44db-8073-1632a9f3b9d2"; // 从安全配置中获取

    //    private final Random random = new Random();
//    private final double successProbability = 0.5; // 50% 的成功概率
    private final CloseableHttpClient httpClient;

    @Autowired
    private VerifySignUtil verifySignUtil;

    public EastTransferComponent() {
        // 创建带有连接池的 HttpClient 实例
        this.httpClient = HttpClients.custom()
                .setMaxConnTotal(200)  // 设置最大连接数
                .setMaxConnPerRoute(200)  // 设置每个路由的最大连接数
                .build();
    }

    ScheduledThreadPoolExecutor scheduledThreadPoolExecutorTransfer =
            new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 2);

    public void doNotifyTransfer(String txid, Integer payStatus, String amount) {
        scheduledThreadPoolExecutorTransfer.schedule(() -> {
            // 执行推送
            try {
                notifyPaymentTransfer(txid, payStatus, amount);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }, 1, TimeUnit.SECONDS);
    }

    public void notifyPaymentTransfer(String payOrderId, Integer payStatus, String amount) throws IOException {
        // 构建请求体参数
        Map<String, Object> params = new HashMap<>();
        // 添加现有字段
        params.put("partner_trx_id", payOrderId);
        params.put("status", payStatus); // 回调状态

        // 添加额外字段
        params.put("merchant_id", "MSF20241027103924003");
        params.put("plat_trx_id", "CA1746075716631531520");
        params.put("charging_fees_method", 1); // 整数类型
        params.put("amount", amount); // 账单金额
        params.put("plat_fee", "2000.00"); // 平台手续费
        params.put("status_msg", "Succeed"); // 状态描述
        params.put("success_time", "2024-01-13 02:51:13"); // 可选字段
        JSONObject jsonObject = new JSONObject(params);
        try {
            HttpPost request = new HttpPost(noticeTransfer);

            String signature = verifySignUtil.verifySign(jsonObject, HMAC_SECRET);
            params.put("signature", signature); // 签名字符串，请替换为实际签名
            String json = new ObjectMapper().writeValueAsString(params);
            StringEntity entity = new StringEntity(json);
            entity.setContentType("application/json");
            request.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(request);
        } catch (Exception e) {
            throw new RuntimeException("代付回调异常:", e);
        }
    }


}
